package com.yuncommunity.runcircle.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.oldfeel.utils.NetUtil;
import com.yuncommunity.runcircle.conf.JsonApi;
import com.yuncommunity.runcircle.conf.Net;
import com.yuncommunity.runcircle.conf.UserInfo;

import java.util.Calendar;
import java.util.TimeZone;

/**
 * Created by oldfeel on 15-7-24.
 */
public class RestartReceiver extends BroadcastReceiver {
    private static final String ACTION_NOTIFICATION_STEP = "com.yuncommunity.runcircle.action_notification_step";
    private static final long DAY = 24 * 60 * 60 * 1000;// 一天

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("com.yuncommunity.runcirle.service.RestartService")) {
            Intent startService = new Intent(context, LocationService.class);
            context.startService(startService);
        } else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED) ||
                intent.getAction().equals(Intent.ACTION_USER_PRESENT) ||
                intent.getAction().equals(Intent.ACTION_PACKAGE_RESTARTED)) {

            Intent stepIntent = new Intent(ACTION_NOTIFICATION_STEP);
            PendingIntent sender = PendingIntent.getBroadcast(context, 0, stepIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            long systemTime = System.currentTimeMillis();

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(systemTime);
// 这里时区需要设置一下，不然会有8个小时的时间差
            calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.HOUR_OF_DAY, 4);//凌晨4点
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
// 选择的定时时间
            long selectTime = calendar.getTimeInMillis();
// 如果当前时间大于设置的时间，那么就从第二天的设定时间开始
            if (systemTime > selectTime) {
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                selectTime = calendar.getTimeInMillis();
            }
// 计算现在时间到设定时间的时间差
            long time = selectTime - systemTime;
// 进行闹铃注册
            AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            manager.setRepeating(AlarmManager.RTC_WAKEUP,
                    time, DAY, sender);
        } else if (intent.getAction().equals("com.yuncommunity.runcircle.action_notification_step")) {
            Net net = new Net(JsonApi.uploadStepData); // 上传步数信息
            net.setParams("date_of_step", UserInfo.getInstance().getStep());
            net.sendPost(new NetUtil.OnJsonResultListener() {
                @Override
                public void onSuccess(String data) {
                }

                @Override
                public void onFail(int code, String data) {
                }
            });
        }
    }
}
